/* af-inet.c
 *
 * establishing a specific AF_INET socket address
 */

#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORTNO 9000

/* this function returns error and exit to the shell from the program */
static void
error(char *msg)
{
	perror(msg);
	exit(1);
}

int main(int argc, char *argv[])
{
	int z; /* status return code */
	int sock_inet; /* inet socket fd */
	struct sockaddr_in sock_addr_inet; /* inet socket address */
	int len_sock_addr_inet; /* inet socket length */
	const unsigned char ip[] = { 127, 0, 0, 1 }; /* lock loopback */

	/* create a AF_INET socket */
	sock_inet = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_inet == -1)
		error("socket()");

	/* form an AF_INET soket */
	bzero((char *) &sock_addr_inet, sizeof(sock_addr_inet));
	sock_addr_inet.sin_family = AF_INET;
	sock_addr_inet.sin_port = htons(PORTNO);
	bcopy(ip, &sock_addr_inet.sin_addr.s_addr, sizeof(ip));

	/* get the socket  address size */
	len_sock_addr_inet = sizeof(sock_addr_inet);

	/* bind socket address to the socket */
	z = bind(sock_inet, (struct sockaddr *) &sock_addr_inet, len_sock_addr_inet);
	if(z == -1)
		error("bind()");

	/* display all bounded sockets */
	system("netstat -npa --tcp 2> /dev/null | sed -n '1,/^Proto/p;/af_inet/p'");

	/* close socket */
	close(sock_inet);

	return 0;
} 
